// const api = require('../../utils/api')
const app = getApp()

Page({
  data: {
    loading: false,
    followedStores: [],
    showUnfollowModal: false,
    unfollowStoreId: null
  },

  onLoad() {
    this.loadFollowedStores()
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadFollowedStores()
  },

  // 加载关注的店铺列表
  async loadFollowedStores() {
    try {
      this.setData({ loading: true })
      
      // 模拟用户ID
      const userId = 1
      
      // 模拟关注的店铺数据
      const mockFollowedStores = [
        {
          id: 1,
          userId: 1,
          storeId: 1,
          receiveNotifications: true,
          followedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前关注
          store: {
            id: 1,
            name: '麦当劳(王府井店)',
            description: '全球知名快餐连锁品牌，提供汉堡、薯条、饮料等美食',
            avatarUrl: '/images/stores/mcdonalds.jpg',
            rating: 4.5,
            monthlySales: 1250,
            deliveryFee: 6.0,
            distance: 1.2,
            ratingStars: Array(Math.floor(4.5)).fill('★'),
            emptyStars: Array(5 - Math.floor(4.5)).fill('★')
          }
        },
        {
          id: 2,
          userId: 1,
          storeId: 3,
          receiveNotifications: true,
          followedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3天前关注
          store: {
            id: 3,
            name: '海底捞火锅(中关村店)',
            description: '服务至上的火锅品牌，新鲜食材，贴心服务',
            avatarUrl: '/images/stores/haidilao.jpg',
            rating: 4.8,
            monthlySales: 2100,
            deliveryFee: 12.0,
            distance: 3.5,
            ratingStars: Array(Math.floor(4.8)).fill('★'),
            emptyStars: Array(5 - Math.floor(4.8)).fill('★')
          }
        },
        {
          id: 3,
          userId: 1,
          storeId: 4,
          receiveNotifications: false,
          followedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前关注
          store: {
            id: 4,
            name: '星巴克咖啡(国贸店)',
            description: '全球知名咖啡连锁品牌，提供优质咖啡和轻食',
            avatarUrl: '/images/stores/starbucks.jpg',
            rating: 4.4,
            monthlySales: 756,
            deliveryFee: 8.0,
            distance: 2.1,
            ratingStars: Array(Math.floor(4.4)).fill('★'),
            emptyStars: Array(5 - Math.floor(4.4)).fill('★')
          }
        }
      ]
      
      this.setData({
        followedStores: mockFollowedStores,
        loading: false
      })
      
    } catch (error) {
      console.error('加载关注店铺失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 跳转到店铺详情页
  goToStore(e) {
    const storeId = e.currentTarget.dataset.storeId
    wx.navigateTo({
      url: `/pages/store/store?id=${storeId}`
    })
  },

  // 跳转到首页
  goToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 切换通知设置
  async toggleNotification(e) {
    const storeId = parseInt(e.currentTarget.dataset.storeId)
    const currentValue = e.currentTarget.dataset.current
    const newValue = e.detail.value
    
    try {
      // 模拟API调用
      await this.mockUpdateNotification(storeId, newValue)
      
      // 更新本地数据
      const followedStores = this.data.followedStores.map(item => {
        if (item.storeId === storeId) {
          return { ...item, receiveNotifications: newValue }
        }
        return item
      })
      
      this.setData({ followedStores })
      
      wx.showToast({
        title: newValue ? '已开启通知' : '已关闭通知',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('更新通知设置失败:', error)
      wx.showToast({
        title: '设置失败',
        icon: 'none'
      })
    }
  },

  // 取消关注店铺
  unfollowStore(e) {
    const storeId = parseInt(e.currentTarget.dataset.storeId)
    this.setData({
      showUnfollowModal: true,
      unfollowStoreId: storeId
    })
  },

  // 确认取消关注
  async confirmUnfollow() {
    try {
      const storeId = this.data.unfollowStoreId
      
      // 模拟API调用
      await this.mockUnfollowStore(storeId)
      
      // 从列表中移除
      const followedStores = this.data.followedStores.filter(item => item.storeId !== storeId)
      
      this.setData({
        followedStores,
        showUnfollowModal: false,
        unfollowStoreId: null
      })
      
      wx.showToast({
        title: '已取消关注',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('取消关注失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 隐藏取消关注弹窗
  hideUnfollowModal() {
    this.setData({
      showUnfollowModal: false,
      unfollowStoreId: null
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 模拟更新通知设置API
  mockUpdateNotification(storeId, receiveNotifications) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`更新店铺 ${storeId} 通知设置为: ${receiveNotifications}`)
        resolve()
      }, 500)
    })
  },

  // 模拟取消关注API
  mockUnfollowStore(storeId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`取消关注店铺: ${storeId}`)
        resolve()
      }, 500)
    })
  },

  // 格式化日期
  formatDate(date) {
    if (!date) return ''
    
    const d = new Date(date)
    const now = new Date()
    const diff = now - d
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    
    if (days === 0) {
      return '今天'
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else {
      const year = d.getFullYear()
      const month = (d.getMonth() + 1).toString().padStart(2, '0')
      const day = d.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}) 